<?php

namespace app\common\model\auth;

use app\common\model\FileModel;
use app\common\model\BaseModel;
use Firebase\JWT\JWT;

class AuthAdminModel extends BaseModel
{
    protected $table = 't_auth_admin';

    //账号状态
    const STATUS_NORMAL = 1;
    const STATUS_FREEZE = 2;
    public $status = [
        self::STATUS_NORMAL => '正常',
        self::STATUS_FREEZE => '冻结'
    ];

    //是否超级管理员
    const IS_ADMIN_YES = 1;
    const IS_ADMIN_NO = 0;
    public $isAdmin = [
        self::IS_ADMIN_YES => '是',
        self::IS_ADMIN_NO => '否'
    ];

    const SEX_UNKNOWN = 0;
    const SEX_MALE = 1;
    const SEX_FEMALE = 2;
    public $sex = [
        self::SEX_UNKNOWN => '未知',
        self::SEX_MALE => '男',
        self::SEX_FEMALE => '女'
    ];

    /**
     * 账号登录
     * @param string $mobile
     * @param string $password
     * @return array|false
     */
    public function login($mobile, $password)
    {
        $adminInfo = $this->where('mobile', $mobile)
            ->field('id,name,file_id,status,is_admin,role_ids,mobile,email,password,sex,birthday,login_time,login_num,create_time')
            ->find();
        if (!$adminInfo) {
            return $this->setError('账号信息不存在或密码错误');
        }
        $adminInfo['file'] = (new FileModel)->getFileByInfo($adminInfo['file_id']);

        if ($adminInfo['password'] != $this->createPassword($password)) {
            return $this->setError('账号信息不存在或密码错误');
        }

        if ($adminInfo['status'] == self::STATUS_FREEZE) {
            return $this->setError('账号已被冻结，请联系管理员');
        }

        $this->where('id', $adminInfo['id'])->update([
            'login_num' => $adminInfo['login_num'] + 1,
            'login_ip' => request()->ip(),
            'login_time' => date('Y-m-d H:i:s'),
        ]);

        (new AuthAdminLogModel)->insert([
            'admin_id' => $adminInfo['id'],
            'login_ip' => request()->ip(),
            'login_num' => $adminInfo['login_num'] + 1,
            'create_time' => date('Y-m-d H:i:s'),
        ]);

        //获取菜单数据
        if ($this->isAdmin($adminInfo)) {
            $menuData = (new AuthMenuModel)->where('type', AuthMenuModel::TYPE_MENU)
                ->order(['sort' => 'DESC', 'id' => 'ASC'])
                ->field('id,parent_id,name,icon,path')
                ->select()->toArray();
            $btnData = (new AuthMenuModel)->where('type', AuthMenuModel::TYPE_BTN)
                ->where("path <> '' AND path <> '#'")
                ->order(['sort' => 'DESC', 'id' => 'ASC'])
                ->field('id,name,path')
                ->select()->toArray();
        } else {
            $ruleMenuData = (new AuthRoleModel)->whereIn('id', explode(',', $adminInfo['role_ids']))
                ->field('menu_ids')
                ->select()->toArray();
            $ruleMenuIds = [];
            foreach ($ruleMenuData as $v) {
                $ruleMenuIds = array_merge($ruleMenuIds, explode(',', $v['menu_ids']));
            }
            $menuData = (new AuthMenuModel)->where('type', AuthMenuModel::TYPE_MENU)
                ->whereIn('id', $ruleMenuIds)
                ->order(['sort' => 'DESC', 'id' => 'ASC'])
                ->field('id,parent_id,name,icon,path')
                ->select()->toArray();
            $btnData = (new AuthMenuModel)->where('type', AuthMenuModel::TYPE_BTN)
                ->whereIn('id', $ruleMenuIds)
                ->where("path <> '' AND path <> '#'")
                ->order(['sort' => 'DESC', 'id' => 'ASC'])
                ->field('id,parent_id,name,icon,path')
                ->select()->toArray();
        }

        unset($adminInfo['password'], $adminInfo['is_admin']);

        return [
            'token' => $this->createToken($adminInfo),
            'admin_info' => $adminInfo,
            'site_theme' => (new AuthAdminConfigModel)->getConfigInfo(AuthAdminConfigModel::TYPE_ADMIN_SITE_THEME, $adminInfo['id']),
            'menu' => [
                'menu' => get_tree($menuData, 0, 'parent_id', 'son_menu'),
                'btn' => $btnData
            ]
        ];
    }

    /**
     * 生成密码
     * @param string $str
     * @return string
     */
    function createPassword($str): string
    {
        return md5($str . config('config.jwt_key'));
    }

    /**
     *
     */
    public function createToken($adminInfo)
    {
        $payload = [
            'admin_id' => $adminInfo['id'],//自定义参数
            'iat' => time(),//签发时间
            'exp' => time() + config('jwt.expire_time'),//过期时间（86400秒 = 1天）
        ];

        return JWT::encode($payload, config('jwt.key'), config('jwt.alg'));
    }

    /**
     * 是否超级管理员
     * @param array $adminInfo
     * @return bool
     */
    public function isAdmin($adminInfo): bool
    {
        return $adminInfo['is_admin'] == self::IS_ADMIN_YES;
    }

}